/* global window */
/* global document */
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'umi'
import { connect } from 'umi'
import { MyLayout, GlobalFooter } from 'components'
import { BackTop, Layout, Drawer } from 'antd'
import { enquireScreen, unenquireScreen } from 'enquire-js'
const { pathToRegexp } = require("path-to-regexp")
import { config, getLocale } from 'utils'
import Error from '../pages/404'
import styles from './PrimaryLayout.less'
import store from 'store'
import MyselfInfoModal from "../pages/admin_user/components/MyselfInfoModal";

const { Content } = Layout
const { Header, Bread, Sider } = MyLayout

@withRouter
@connect(({ app, loading }) => ({ app, loading }))
class PrimaryLayout extends PureComponent {
  state = {
    isMobile: false,
    showEditUser: false, //是否展示当前登录用户编辑框
    myselfInfo: {}, //当前登录用户
  }

  componentDidMount() {
    this.enquireHandler = enquireScreen(mobile => {
      const { isMobile } = this.state
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        })
      }
    })

    //设置监听器
    setInterval(()=>{
      const isInit = store.get('isInit') || null
      if(isInit) {
        this.props.dispatch({
          type: 'app/queryNotification',
          payload: {},
        })
      }
    }, 10000);
  }

  componentWillUnmount() {
    unenquireScreen(this.enquireHandler)
  }

  onCollapseChange = collapsed => {
    this.props.dispatch({
      type: 'app/handleCollapseChange',
      payload: collapsed,
    })
  }

  render() {
    const { app, location, dispatch, children } = this.props
    const { theme, collapsed, notifications,notification,notificationVisible } = app
    const user = store.get('user') || {}
    const permissions = store.get('permissions') || {}
    const routeList = store.get('routeList') || []
    const { isMobile } = this.state
    const { onCollapseChange } = this

    // Localized route name.

    const lang = getLocale()
    const newRouteList =
      lang !== 'en'
        ? routeList.map(item => {
            const { name, ...other } = item
            return {
              ...other,
              key: item.id,
              name: (item[lang] || {}).name || name,
            }
          })
        : routeList

    // Find a route that matches the pathname.
    const currentRoute = newRouteList.find(
      _ => _.route && pathToRegexp(_.route).exec(location.pathname)
    )

    // Query whether you have permission to enter this page
    // const hasPermission = currentRoute
    //   ? permissions.visit.includes(currentRoute.id)
    //   : false

    const hasPermission = true

    // MenuParentId is equal to -1 is not a available menu.
    const menus = newRouteList.filter(_ => _.menuParentId !== '-1' && _.visible)

    const headerProps = {
      menus,
      collapsed,
      notifications,
      notification,
      notificationVisible,
      onCollapseChange,
      avatar: user?.avatar,
      username: user?.username,
      fixed: config.fixedHeader,
      onAllNotificationsRead() {
        dispatch({ type: 'app/allNotificationsRead' })
      },
      onNotificationsRead(item) {
        dispatch({type:'app/notificationsRead', payload: {id: item.id}})
      },
      onShowNotification(item) {
        dispatch({type:'app/handleShowNotification', payload: {notification: item, notificationVisible: true}})
      },
      onNotificationCancel() {
        dispatch({type:'app/updateState', payload: { notificationVisible: false}})
      },
      onSignOut() {
        dispatch({ type: 'app/signOut' })
      },
      onRefresh() {
         store.remove("isInit");
         window.location.reload();
      },
      //编辑自己用户信息
      onEditSelf: () => {
        this.props.dispatch({
          type: 'app/queryMyselfInfo',
          payload: {},
        }).then((data)=>{
          this.state.myselfInfo = data;
          this.state.showEditUser = true;
        });
      }
    }

    const siderProps = {
      theme,
      menus,
      isMobile,
      collapsed,
      onCollapseChange,
      onThemeChange(theme) {
        dispatch({
          type: 'app/handleThemeChange',
          payload: theme,
        })
      },
    }

    const userEditProps = {
      open: this.state.showEditUser,
      item: this.state.myselfInfo,
      title: "资料编辑",
      onCancel: (e) => {
        this.state.showEditUser = false
      },
      onOk: (data) => {
        dispatch({
          type: 'app/updateSelfUser',
          payload: data,
        }).then((r)=>{
          this.state.showEditUser=false
        })
      }
    }

    return (
      <Fragment>
        <Layout>
          {isMobile ? (
            <Drawer
              maskClosable
              closable={false}
              onClose={onCollapseChange.bind(this, !collapsed)}
              visible={!collapsed}
              placement="left"
              width={200}
              style={{
                padding: 0,
                height: '100vh',
              }}
            >
              <Sider {...siderProps} collapsed={false} />
            </Drawer>
          ) : (
            <Sider {...siderProps} />
          )}
          <div
            className={styles.container}
            style={{ paddingTop: config.fixedHeader ? 72 : 0 }}
            id="primaryLayout"
          >
            <Header {...headerProps} />
            <Content className={styles.content}>
              <Bread routeList={newRouteList} />
              {hasPermission ? children : <Error />}
            </Content>
            <BackTop
              className={styles.backTop}
              target={() => document.querySelector('#primaryLayout')}
            />
            <GlobalFooter
              className={styles.footer}
              copyright={config.copyright}
            />
          </div>
          <MyselfInfoModal {...userEditProps} />
        </Layout>
      </Fragment>
    )
  }
}

PrimaryLayout.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.object,
}

export default PrimaryLayout
